import { useEffect, useRef, useState } from 'react';

const FullScreenComponent = () => {
  const ref = useRef(null);
  const [isFullscreen, setIsFullscreen] = useState(false);

  // 进入全屏
  const enterFullscreen = async () => {
    if (ref.current && !isFullscreen) {
      await ref.current.requestFullscreen();
      setIsFullscreen(true);
      // 绑定 ESC 监听
      document.addEventListener('keydown', handleEsc);
    }
  };

  // 退出全屏
  const exitFullscreen = async () => {
    if (document.fullscreenElement) {
      await document.exitFullscreen();
      setIsFullscreen(false);
      // 移除监听
      document.removeEventListener('keydown', handleEsc);
    }
  };

  // ESC 事件处理
  const handleEsc = (e) => {
    if (e.key === 'Escape') {
      e.preventDefault(); // 阻止默认退出全屏（可选）
      console.log('捕获到 ESC 键');
      // 自定义逻辑（如先执行操作，再退出全屏）
      exitFullscreen();
    }
  };

  // 监听全屏状态变化（处理浏览器前缀）
  useEffect(() => {
    const handleFullscreenChange = () => {
      setIsFullscreen(!!document.fullscreenElement);
    };
    // 绑定全屏状态变化事件（兼容前缀）
    document.addEventListener('fullscreenchange', handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
    return () => {
      document.removeEventListener('fullscreenchange', handleFullscreenChange);
      document.removeEventListener('webkitfullscreenchange', handleFullscreenChange);
    };
  }, []);

  return (
    <div>
      <button onClick={enterFullscreen}>进入全屏</button>
      <div ref={ref} style={{ width: '100%', height: '100vh', background: 'red' }} />
    </div>
  );
};

export default FullScreenComponent